package com.controller;

import com.bean.Recoding;
import com.bean.User;
import com.service.AccenderService;
import com.service.CompletedService;
import com.service.RecodingService;
import com.service.UserService;
import com.utils.PageBean;
import com.utils.SendMail;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Controller
public class CompletedController {
    @Resource
    RecodingService recodingService;
    @Resource
    CompletedService completedService;
    @Resource
    UserService userService;
    @Resource
    AccenderService accenderService;

    @RequestMapping("completed/listCompleted")
    public ModelAndView listCompleted(ModelAndView modelAndView, @RequestParam(value = "pageNo", defaultValue = "1") int pageNo) {
        List<Recoding> recodingList = recodingService.recodingList();
        List<User> userList = userService.queryUserList();
        PageBean pageBean = completedService.findByPage(pageNo, 5);
        modelAndView.addObject("userList", userList);
        modelAndView.addObject("recodingList", recodingList);
        modelAndView.addObject("pageBean", pageBean);
        modelAndView.setViewName("listCompleted");
        return modelAndView;
    }

    @RequestMapping(value = "completed/addCompleted", method = RequestMethod.POST)
    public ModelAndView addRecoding(@RequestParam("id") int id, @RequestParam("username") String username, @RequestParam("contact") String contact,
                                    @RequestParam("address") String address, @RequestParam("question") String question, @RequestParam("date") Date date,
                                    @RequestParam("accender_name") String accender_name, @RequestParam("sender") String sender) throws Exception {
        completedService.addCompleted(id, username, question, contact, address, date, accender_name, sender);
        recodingService.deleteRecodingById(id);
        try {
            if (accenderService.queryEmailByName(accender_name) != null) {
                String e_mail = accenderService.queryEmailByName(accender_name);
                SendMail.sendEMail(e_mail, "任务完成", sender + "已经确认你已完成出勤任务。");
            } else {
                SendMail.sendEMail("1426061489@qq.com", "错误数据", "派单人员确认了一条错误的出勤数据,请前往数据库查看");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("redirect:/recoding/listRecoding");
        return modelAndView;
    }

}
